const express = require('express')
const router = express.Router()
const axios = require('axios');
const dotenv = require('dotenv');
// 导入数据库模块
const db = require("../config/database");
// 导入Token包
const jwt = require("jsonwebtoken");
// 导入配置文件
const config = require("../config");
dotenv.config();


// 假设的微信应用配置，你需要替换成你自己的
const WECHAT_APPID = process.env.WECHAT_APPID;
const WECHAT_REDIRECT_URI = process.env.WECHAT_REDIRECT_URI; // 你的回调URL
const WECHAT_SECRET = process.env.WECHAT_SECRET;

// 登录按钮触发的路由
router.post('/wechat-login', (req, res) => {
  // 构建微信OAuth 2.0授权URL
  const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${WECHAT_APPID}&redirect_uri=${encodeURIComponent(WECHAT_REDIRECT_URI)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
  // 重定向用户到微信授权页面
  res.redirect(authUrl);
});

// 微信回调路由
router.get('/wechat-callback', async (req, res) => {
  try {
    const code = req.query.code;
    const accessTokenUrl = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${WECHAT_APPID}&secret=${WECHAT_SECRET}&code=${code}&grant_type=authorization_code`;
    const accessTokenResponse = await axios.get(accessTokenUrl);
    const { access_token, openid } = accessTokenResponse.data;
    const userInfoUrl = `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN`;
    const userInfoResponse = await axios.get(userInfoUrl);
    const userInfo = userInfoResponse.data;

    const query = 'SELECT * FROM ev_users WHERE openid = ?';
    const [rows] = await db.query(query, [openid]);

    if (rows.length > 0) {
      const ev_user = { ...rows[0], openid: ' ', password: '', user_pic: '' };
      const tokenStr = jwt.sign(ev_user, jwtSecretKey, { expiresIn });
      res.send({ status: 0, message: "登陆成功", token: "Bearer " + tokenStr });
    } else {
      const insertQuery = 'INSERT INTO ev_users (openid, nickname, avatar) VALUES (?, ?, ?)';
      await db.query(insertQuery, [openid, userInfo.nickname, userInfo.headimgurl]);
      console.log('新用户已创建');
      const ev_user = { openid, nickname: userInfo.nickname, avatar: userInfo.headimgurl, password: '', user_pic: '' };
      const tokenStr = jwt.sign(ev_user, config.jwtSecretKey, { expiresIn: config.expiresIn, });
      res.send({ status: 0, message: "登陆成功", token: "Bearer " + tokenStr });
    }
  } catch (error) {
    console.error(error);
    res.status(500).send('Login failed');
  } finally {
    db.end();
  }
});
module.exports = router